package com.nowcoder.community.service;

import com.nowcoder.community.Utils.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

/**
 * 点赞功能业务层
 * @author panxingyu
 */
@Service
public class LikeService {
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 点赞
     *
     * @param userId     点赞人的用户ID
     * @param entityType 实体类型
     * @param entityId   实体ID
     * @param entityUserId 被点赞的用户ID
     */
    public void like(int userId, int entityType, int entityId, int entityUserId) {
        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
                String userLikeKey = RedisKeyUtil.getUserLikeKey(entityUserId);
                // 判断当前用户是否已经点赞
                Boolean member = operations.opsForSet().isMember(entityLikeKey, userId);
                // 开启事务
                operations.multi();
                if (member) {
                    // 取消点赞
                    operations.opsForSet().remove(entityLikeKey, userId);
                    // 点赞数减少
                    operations.opsForValue().decrement(userLikeKey);
                } else {
                    // 点赞
                    operations.opsForSet().add(entityLikeKey, userId);
                    // 增加点赞数
                    operations.opsForValue().increment(userLikeKey);
                }
                return operations.exec();
            }
        });
    }
    /**
     * 查询某个实体的点赞数量
     */
    public Long findEntityLikeCount(int entityType, int entityId) {
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        return redisTemplate.opsForSet().size(entityLikeKey);
    }
    /**
     * 查询某人对某实体的点赞状态
     */
    public int findEntityLikeStatus(int userId, int entityType, int entityId) {
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        // 如果已经在 Redis 中，说明已经点赞了，设置为1，否则设置为0
        // 设置为 int 的目的在于对结果的扩展，比如 -1 表示踩
        return redisTemplate.opsForSet().isMember(entityLikeKey, userId) ? 1 : 0;
    }
    /**
     * 查询某个用户获得的赞
     */
    public int findUserLikeCount(int userId) {
        String userLikeKey = RedisKeyUtil.getUserLikeKey(userId);
        Integer count = (Integer) redisTemplate.opsForValue().get(userLikeKey);
        return count == null ? 0 : count;
    }
}
